<?php

namespace app\admin\controller;

use app\admin\model\Cate as cateModel;
use app\admin\validate\hoscateValidate;
use tool\Log;

class Cate extends Base
{
    // 栏目列表
    public function index()
    {
        $cate = new cateModel();
        $list = $cate->getCatesList();

        $this->assign([
            'tree' => makeTree($list['data'])
        ]);

        return $this->fetch();
    }

    // 添加栏目
    public function add()
    {
        if (request()->isAjax()) {

            $param = input('post.');

            $validate = new hoscateValidate();
            if(!$validate->check($param)) {
                return ['code' => -1, 'data' => '', 'msg' => $validate->getError()];
            }

            $cateModel = new cateModel();
            $res = $cateModel->addCate($param);

            Log::write("添加栏目：" . $param['classname']);

            return json($res);
        }

        $this->assign([
            'pname' => input('param.pname'),
            'pid' => input('param.pid')
        ]);

        return $this->fetch();
    }

    // 编辑栏目
    public function edit()
    {
        if (request()->isAjax()) {

            $param = input('post.');

            $validate = new hoscateValidate();
            if(!$validate->check($param)) {
                return ['code' => -1, 'data' => '', 'msg' => $validate->getError()];
            }

            $cateModel = new cateModel();
            $res = $cateModel->editCate($param);

            Log::write("编辑栏目：" . $param['classname']);

            return json($res);
        }

        $id = input('param.id');
        $pid = input('param.pid');

        $cateModel = new cateModel();

        if (0 == $pid) {
            $pCate = '顶级栏目';
        } else {
            $pCate = $cateModel->getCateInfoById($pid)['data']['classname'];
        }

        $this->assign([
            'cate_info' => $cateModel->getCateInfoById($id)['data'],
            'p_cate' => $pCate
        ]);

        return $this->fetch();
    }

    // 删除栏目
    public function delete()
    {
        if (request()->isAjax()) {

            $id = input('param.id');

            $cateModel = new cateModel();
            $res = $cateModel->deleteCateById($id);

            Log::write("删除栏目：" . $id);

            return json($res);
        }
    }
}